package controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import entity.App_category;
import entity.App_info;
import entity.App_version;
import entity.Data_dictionary;
import entity.Dev_user;
import service.AppInfoService;
import entity.PageSupport;


@Controller
@RequestMapping("/Query")
public class Appinfo_Controller {

	@Autowired
	private AppInfoService appInfoService;
	
	
	@RequestMapping("/list")
	public String query(HttpServletRequest request) {
		String querySoftwareName = request.getParameter("querySoftwareName");
		String queryStatus = request.getParameter("queryStatus");
		String queryFlatformId = request.getParameter("queryFlatformId");
		String queryCategoryLevel1 = request.getParameter("queryCategoryLevel1");
		String queryCategoryLevel2 = request.getParameter("queryCategoryLevel2");
		String queryCategoryLevel3 = request.getParameter("queryCategoryLevel3");
		String pageIndex = request.getParameter("pageIndex");
		//��ǰҳ��
		int currentPageNo = 1;
		
		if (pageIndex != null) {
			currentPageNo = Integer.valueOf(pageIndex);
		}
		
		
		
		Integer queryStatus1 = null;
		if(queryStatus != null && !queryStatus.equals("")){
			queryStatus1 = Integer.valueOf(queryStatus);
		}
		Integer quer1 = null;
		if(queryCategoryLevel1 != null && !queryCategoryLevel1.equals("")){
			quer1 = Integer.valueOf(queryCategoryLevel1);
		}
		Integer quer2 = null;
		if(queryCategoryLevel2 != null && !queryCategoryLevel2.equals("")){
			quer2 = Integer.valueOf(queryCategoryLevel2);
		}
		Integer quer3 = null;
		if(queryCategoryLevel3 != null && !queryCategoryLevel3.equals("")){
			quer3 = Integer.valueOf(queryCategoryLevel3);;
		}
		Integer queryFlatformId1 = null;
		if(queryFlatformId != null && !queryFlatformId.equals("")){
			queryFlatformId1 = Integer.valueOf(queryFlatformId);;
		}
		
		
		
		
		PageSupport pages = new PageSupport();
		
		int zoushu = appInfoService.PageCount(querySoftwareName, queryStatus1, quer1, quer2, quer3, queryFlatformId1);
	
		int yeshu =zoushu % 5 == 0 ? (zoushu/5):(zoushu/5)+1;
		pages.setTotalCount(zoushu);
		pages.setTotalPageCount(yeshu);
		pages.setCurrentPageNo(currentPageNo);
		
		List<App_info> list = appInfoService.query(querySoftwareName, queryStatus1, quer1, quer2, quer3, queryFlatformId1, pages);
		
		List<Data_dictionary> list2 = appInfoService.Platform();
		
		List<Data_dictionary> list3 = appInfoService.App();
		
		List<App_category> list4 = appInfoService.One();
		
		
		if (queryCategoryLevel1 != null && !queryCategoryLevel1.equals("")) {
			List<App_category> categoryLevel2List = appInfoService.Two(quer1);
			request.setAttribute("categoryLevel2List", categoryLevel2List);
		}
		
		if (queryCategoryLevel2 != null && !queryCategoryLevel2.equals("")) {
			List<App_category> categoryLevel3List = appInfoService.Two(quer2);
			request.setAttribute("categoryLevel3List", categoryLevel3List);
		}
		request.setAttribute("appInfoList", list);
		request.setAttribute("queryStatus", queryStatus1);
		request.setAttribute("querySoftwareName",querySoftwareName);
		request.setAttribute("queryCategoryLevel1", quer1);
		request.setAttribute("queryCategoryLevel2", quer2);
		request.setAttribute("queryCategoryLevel3", quer3);
		request.setAttribute("queryFlatformId", queryFlatformId1);
		request.setAttribute("pages", pages);
		request.setAttribute("categoryLevel1List", list4);
		request.setAttribute("statusList", list3);
		request.setAttribute("flatFormList", list2);
		return "developer/appinfolist";
	}
	
	
	@RequestMapping("/leve")
	@ResponseBody
	public String classification(HttpServletRequest request) {
		String pid = request.getParameter("pid");
		List<App_category> list = appInfoService.Two(Integer.valueOf(pid));
		return JSON.toJSONString(list);
	}
	
	
	@RequestMapping("/appview")
	public String appview(HttpServletRequest request) {
		String id = request.getParameter("id");
		App_info app_info = appInfoService.Appquery(Integer.valueOf(id));//�鿴��ϸ��Ϣ
		List<App_version> list = appInfoService.Appchaxun(Integer.valueOf(id));//�鿴��ʷ�汾
		request.setAttribute("appVersionList", list);
		request.setAttribute("appInfo", app_info);
		return "developer/appinfoview";
	}
	
	
	@RequestMapping("/dele")
	@ResponseBody
	public String dele(HttpServletRequest request) {
		String id = request.getParameter("id");
		int i = appInfoService.dele(Integer.valueOf(id));
		appInfoService.delemodiy(Integer.valueOf(id));
		String flage = "";
		if (i>0) {
			flage = "true";
		}else {
			flage = "false";
		}
		return JSON.toJSONString(flage);
	}
	
	
	@RequestMapping("/appinfoadd")
	public String Add(HttpServletRequest request) {
		return "developer/appinfoadd";
	}
	
	@RequestMapping("/Add")
	@ResponseBody
	public String Addquery(HttpServletRequest request) {
		String typecode = request.getParameter("tcode");
		System.out.println(typecode);
		//����ҳ������ƽ̨�������ѯ
		List<Data_dictionary> list = appInfoService.Addping(typecode);
		return JSON.toJSONString(list);
	}
	

	@RequestMapping("/Add1")
	@ResponseBody
	public String Add1(HttpServletRequest request) {
		List<App_category> list = appInfoService.One1();
		return JSON.toJSONString(list);
	}

	@RequestMapping("/Add2")
	@ResponseBody
	public String Add2(HttpServletRequest request) {
		String pid = request.getParameter("pid");
		List<App_category> list = appInfoService.Two(Integer.valueOf(pid));
		return JSON.toJSONString(list);
	}
	
	
	@RequestMapping("/upload")
	public String upload(App_info appInfo,HttpSession session,HttpServletRequest request,
			@RequestParam(value="a_logoPicPath",required= false) MultipartFile attach)throws Exception{
		String idPicPath = null;
		String logoPicPath=null;
		
		if (!attach.isEmpty()) {
			String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
			String oldFileName = attach.getOriginalFilename();
			String prefix = FilenameUtils.getExtension(oldFileName);
			int filesize = 200000;
			System.out.println("size=========================="+attach.getSize());
			if (attach.getSize()>filesize) {
				request.setAttribute("fileUploadError", "不能超過200KB");
				return "developer/appinfoadd";
			}else if (prefix.equalsIgnoreCase("jpg")
					 || prefix.equalsIgnoreCase("png")
					 || prefix.equalsIgnoreCase("jpeg")
					 || prefix.equalsIgnoreCase("pneg")) {
				String fileName = appInfo.getAPKName()+"jpg";
				System.out.println("fileName========="+attach.getName());
				File targefile = new File(path,fileName);
				if (!targefile.exists()) {
					targefile.mkdirs();
				}
				
				try {
					attach.transferTo(targefile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute("fileUploadError", "上传失败！");
					return "developer/appinfoadd";
				}
				logoPicPath = request.getContextPath()+"/statics/uploadfiles/"+fileName;
				idPicPath = path+File.separator+fileName;
			}else {
				return "developer/appinfoadd";
			}
		}
		Dev_user devuser = (Dev_user) session.getAttribute("devUserSession");
		appInfo.setDevId(devuser.getId());
		appInfo.setCreationDate(new Date());
		appInfo.setLogoPicPath(logoPicPath);
		appInfo.setLogoLocPath(idPicPath);
		appInfo.setStatus(1);
		try {
			int i = appInfoService.insert(appInfo);
			if(i>0){
				return "redirect:/Query/list";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "developer/appinfoadd";
	}
	
	
	@RequestMapping("/apkexist")
	@ResponseBody
	public String Verification(HttpServletRequest request) {
		String a = "";
		String APKName = request.getParameter("APKName");
		int count = appInfoService.Verification(APKName);
		System.out.println("APK名称："+APKName);
		System.out.println(count);
		
		if(APKName.equals("")) {
			a="empty";
		}else if (count > 0) {
			a="exist";
		}else {
			a="noexist";
		}
		return JSON.toJSONString(a);
	}
	
	
	@RequestMapping("/appinfomodify")
	public String modify(HttpServletRequest request) {
		String id = request.getParameter("id");
		
		App_info appInfo = appInfoService.Appquery(Integer.valueOf(id));
		request.setAttribute("appInfo", appInfo);
		return "developer/appinfomodify";
	}
	
	
	@RequestMapping(value="/categorylevellist.json",method=RequestMethod.GET)
	@ResponseBody
	public String getAppCategoryList (@RequestParam String pid){
		if(pid.equals("")) 
		   pid = null;
		List<App_category> categoryLevelList = appInfoService.getAppCategoryListByParentId(pid==null?null:Integer.parseInt(pid));
		System.out.println("��С"+categoryLevelList.size());
		return JSON.toJSONString(categoryLevelList);
	}
	
	
	@RequestMapping("/appversionadd")
	public String appversionadd(HttpServletRequest request) {
		String id = request.getParameter("id");
		List<App_version> list = appInfoService.Appchaxun(Integer.valueOf(id));//�鿴��ʷ�汾
		
		request.setAttribute("appId", id);
		request.setAttribute("appVersionList", list);
		return "developer/appversionadd";
	}
	
	
	@RequestMapping(value="/addversionsave",method=RequestMethod.POST)
	public String addversionsave(App_version appVersion,HttpSession session,HttpServletRequest request,
			@RequestParam(value="a_downloadLink",required= false) MultipartFile attach ) {
		String downloadLink =  null;
		String apkLocPath = null;
		String apkFileName = null;
		if(!attach.isEmpty()){
			String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
			String oldFileName = attach.getOriginalFilename();
			String prefix = FilenameUtils.getExtension(oldFileName);
			if(prefix.equalsIgnoreCase("apk")){
				 String apkName = null;
				 try {
					 System.out.println("appid---------"+appVersion.getAppId());
					apkName = appInfoService.ApkName(appVersion.getAppId()).getAPKName();
					System.out.println("apk����-------"+apkName);
				 } catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				 }
				 if(apkName == null || "".equals(apkName)){
					 return "redirect:/Query/appversionadd?id="+appVersion.getAppId();
				 }
				 apkFileName = apkName + "-" +appVersion.getVersionNo() + ".apk";
				 File targetFile = new File(path,apkFileName);
				 if(!targetFile.exists()){
					 targetFile.mkdirs();
				 }
				 try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute("fileUploadError", "文件格式不正确！");
					return "redirect:/Query/appversionadd?id="+appVersion.getAppId();
				} 
				downloadLink = request.getContextPath()+"/statics/uploadfiles/"+apkFileName;
				apkLocPath = path+File.separator+apkFileName;
			}else{
				request.setAttribute("fileUploadError", "文件格式不正确！");
				return "redirect:/Query/appversionadd?id="+appVersion.getAppId();
			}
		}
		Dev_user devuser = (Dev_user) session.getAttribute("devUserSession");
		appVersion.setCreatedBy(devuser.getId());
		appVersion.setCreationDate(new Date());
		appVersion.setDownloadLink(downloadLink);
		appVersion.setApkLocPath(apkLocPath);
		appVersion.setApkFileName(apkFileName);
		try {
			int i = appInfoService.AddBan(appVersion);
			if(i>0){
				appInfoService.updateVersionId(appVersion.getId(), appVersion.getAppId());	
				return "redirect:/Query/list";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "redirect:/Query/appversionadd?id="+appVersion.getAppId();
	}
	
	//�޸�ͼƬ·��Ϊnull
	@RequestMapping("/delfile")
	@ResponseBody
	public String updateimges(HttpServletRequest request) {
		String id = request.getParameter("id");
		int i = appInfoService.updateimages(Integer.valueOf(id));
		String flag = "";
		if (i>0) {
			flag = "success";
		}else {
			flag = "failed";
		}
		return JSON.toJSONString(flag);
	}
	
	//�޸�APP������Ϣ
	@RequestMapping(value="/appinfomodifysave",method=RequestMethod.POST)
	public String information(App_info appInfo,HttpSession session,HttpServletRequest request,
			@RequestParam(value="attach",required= false) MultipartFile attach) {
        System.out.println("id=================="+appInfo.getId());
		String idPicPath = null;
		String logoPicPath=null;
		//�ж��ļ��Ƿ�Ϊ��
		if (!attach.isEmpty()) {
			String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
			String oldFileName = attach.getOriginalFilename();//ԭ�ļ���
			String prefix = FilenameUtils.getExtension(oldFileName);//ԭ�ļ���׺
			int filesize = 200000;//�����ļ��ܴ�С���ܳ���200KB
			System.out.println("size=========================="+attach.getSize());
			if (attach.getSize()>filesize) {//�ϴ����ļ����ܳ���200KB
				request.setAttribute("fileUploadError", "�ϴ��ļ����ó���200KB");
				return "developer/appinfoadd";
			}else if (prefix.equalsIgnoreCase("jpg")
					 || prefix.equalsIgnoreCase("png")
					 || prefix.equalsIgnoreCase("jpeg")
					 || prefix.equalsIgnoreCase("pneg")) {//�ж�ͼƬ��ʽ
				String fileName = appInfo.getAPKName()+"jpg";//�ϴ�LOGOͼƬ����
				System.out.println("fileName========="+attach.getName());
				File targefile = new File(path,fileName);
				if (!targefile.exists()) {
					targefile.mkdirs();
				}
				//����
				try {
					attach.transferTo(targefile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute("fileUploadError", "�ϴ�ʧ��!");
					return "redirect:/Query/appinfomodify?id="+appInfo.getId();				}
				logoPicPath = request.getContextPath()+"/statics/uploadfiles/"+fileName;
				idPicPath = path+File.separator+fileName;
			}else {
				request.setAttribute("fileUploadError", "�ϴ�ͼƬ��ʽ����ȷ");
				return "redirect:/Query/appinfomodify?id="+appInfo.getId();
			}
		}
		if (logoPicPath != null) {
			Dev_user devuser = (Dev_user) session.getAttribute("devUserSession");
			appInfo.setModifyBy(devuser.getId());
			appInfo.setModifyDate(new Date());
			appInfo.setLogoPicPath(logoPicPath);
			appInfo.setLogoLocPath(idPicPath);
		}
		try {
			int i = appInfoService.updatexinxi(appInfo);
			if(i>0){
				return "redirect:/Query/list";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/Query/appinfomodify?id="+appInfo.getId();
	}
	
	//�޸İ汾��Ϣ
	@RequestMapping("/appversionmodify")
	public String appinfomodify(HttpServletRequest request) {
		String vid = request.getParameter("vid");
		String aid = request.getParameter("aid");
		List<App_version> list = appInfoService.Appchaxun(Integer.valueOf(aid));//�鿴��ʷ�汾
		App_version app_version = appInfoService.querybanben(Integer.valueOf(vid));//��ʾ�汾��Ϣ
		request.setAttribute("appVersion", app_version);
		request.setAttribute("appVersionList", list);
		return "developer/appversionmodify";
	}
	
	//ʹ��ajaxɾ���汾
	@RequestMapping("/delebanben")
	@ResponseBody
	public String delebanben(HttpServletRequest request) {
		String id = request.getParameter("id");
		int i = appInfoService.updatebanben(Integer.valueOf(id));
		String flage = "";
		if (i>0) {
			flage = "success";
		}else {
			flage = "failed";
		}
		return JSON.toJSONString(flage);
	}
	
	//app上下架
	@RequestMapping("/sale")
	@ResponseBody
	public Object uplower(@RequestParam(value="id") Integer id,
						  @RequestParam(value="status") Integer status) {		
		
		
		return JSON.toJSONString(appInfoService.uplower(status, id));
	}
	
	//修改版本信息
		@RequestMapping("/appversionmodifysave")
		public String updatebanben(App_version appVersion,HttpSession session,HttpServletRequest request,
				@RequestParam(value="attach",required= false) MultipartFile attach ) {
			String downloadLink =  null;
			String apkLocPath = null;
			String apkFileName = null;
			if(!attach.isEmpty()){
				String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
				String oldFileName = attach.getOriginalFilename();//原文件名
				String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
				System.out.println("vid==="+appVersion.getId()+"aid====="+appVersion.getAppId());
				if(prefix.equalsIgnoreCase("apk")){//apk文件命名：apk名称+版本号+.apk
					 String apkName = null;
					 try {
						 System.out.println("appid---------"+appVersion.getAppId());
						apkName = appInfoService.ApkName(appVersion.getAppId()).getAPKName();
						System.out.println("apk名称-------"+apkName);
					 } catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
						request.setAttribute("fileUploadError", "APK格式不正确！");
						return "redirect:/Query/appversionmodify?vid="+appVersion.getId()
						 +"&aid="+appVersion.getAppId();
					 }
					 if(apkName == null || "".equals(apkName)){
						 request.setAttribute("fileUploadError", "APK信息不完整！");
						 return "redirect:/Query/appversionmodify?vid="+appVersion.getId()
						 +"&aid="+appVersion.getAppId();
					 }
					 apkFileName = apkName + "-" +appVersion.getVersionNo() + ".apk";
					 File targetFile = new File(path,apkFileName);
					 if(!targetFile.exists()){
						 targetFile.mkdirs();
					 }
					 try {
						attach.transferTo(targetFile);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						request.setAttribute("fileUploadError", "上传失败！");
						return "redirect:/Query/appversionmodify?vid="+appVersion.getId()
						 +"&aid="+appVersion.getAppId();
					} 
					downloadLink = request.getContextPath()+"/statics/uploadfiles/"+apkFileName;
					apkLocPath = path+File.separator+apkFileName;
				}else{
					request.setAttribute("fileUploadError", "上传文件格式不正确！");
					return "redirect:/Query/appversionmodify?vid="+appVersion.getId()
					 +"&aid="+appVersion.getAppId();
				}
			}
			if (apkLocPath != null) {
				Dev_user devuser = (Dev_user) session.getAttribute("devUserSession");
				appVersion.setModifyBy(devuser.getId());
				appVersion.setModifyDate(new Date());
				appVersion.setDownloadLink(downloadLink);
				appVersion.setApkLocPath(apkLocPath);
				appVersion.setApkFileName(apkFileName);
			}
			try {
				int i = appInfoService.updatemodiy(appVersion);
				if(i>0){
					return "redirect:/Query/list";
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "redirect:/Query/appversionmodify?vid="+appVersion.getId()
			 +"&aid="+appVersion.getAppId();
		}
}
